<template>
  <view v-if="shenheStatus == 0" class="login"></view>
  <Shenhe v-else-if="shenheStatus == 1" :isShowTitle="true"></Shenhe>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import { getStoreSwitch } from "@/api/system";

export default {
  components: {
    Shenhe
  },
  data() {
    return {};
  },
  onLoad() {
    let params = this.getRequestParams();
    if (params.code) {
      this.getOpenId(params.code);
    } else {
      uni.showToast({
        title: "授权失败",
        icon: "none"
      });
      setTimeout(() => {
        let pagesUrl = uni.getStorageSync("pagesUrl");
        if (pagesUrl) {
          uni.removeStorageSync("pagesUrl");
          this.$utils.toUrl(pagesUrl, "reLaunch");
        } else {
          this.$utils.goBack(2);
        }
      }, 1000);
    }
  },
  methods: {
    // 解析code获得openid
    async getOpenId(code) {
      let hasOneStroe = false;

      const res = await this.$allrequest.user.getOpenidByCode({ code });
      if (res.code == 0) {
        uni.showToast({
          title: "授权成功",
          icon: "none"
        });

        try {
          const ress = await getStoreSwitch();
          if (ress.data.is_switch_store) {
            uni.removeStorageSync("storeMdData");
            this.$store.commit("setStoreId", ress.data.store_id);
            this.$store.commit("setCopyright", ress.data.copyright);
            hasOneStroe = true;
          }
        } catch (error) {}

        setTimeout(() => {
          let pagesUrl = uni.getStorageSync("pagesUrl");
          if (pagesUrl) {
            uni.removeStorageSync("pagesUrl");
            this.$utils.toUrl(pagesUrl, "reLaunch");
          } else {
            if (hasOneStroe)
              return this.$utils.toUrl("/pages/my/my", "reLaunch");

            this.$utils.goBack(2);
          }
        }, 1000);
      }
    },
    // 解析网址
    getRequestParams() {
      let url = location.href;
      let requestParams = {};
      if (url.indexOf("?") !== -1) {
        let str = url.substr(url.indexOf("?") + 1); //截取?后面的内容作为字符串
        let strs = str.split("&"); //将字符串内容以&分隔为一个数组
        for (let i = 0; i < strs.length; i++) {
          requestParams[strs[i].split("=")[0]] = decodeURI(
            strs[i].split("=")[1]
          );
          // 将数组元素中'='左边的内容作为对象的属性名，'='右边的内容作为对象对应属性的属性值
        }
      }
      return requestParams;
    }
  }
};
</script>